<!-- RTC 11-15 -->
<template>
  <div class="video-chat">
    <!-- <div v-if="isRoomEmpty">
      <p>{{ roomStatusText }}</p>
    </div> -->
    <!-- 视频双端显示 -->
    <div class="video_box">
      <div class="self_video">
        <!-- <div class="text_tip">我：<span class="userId">{{ userId }}</span></div> -->
        <video ref="localVideo" autoplay muted="muted"></video>
      </div>
      <div class="remote_video" @click="switchPosition">
        <!-- <div class="text_tip">对方：<span class="userId">{{ oppositeUserId }}</span></div> -->
        <video ref="remoteVideo" muted="muted"></video>
      </div>
      <!-- 加入房间按钮 -->
      <div class="join_room_btn">
        <button @click="joinRoomHandle" v-if="!isJoin">加入通话</button>
        <button @click="exitRoomHandle">退出通话</button>
      </div>
    </div>
    <!-- 日志打印 -->
    <!-- <div class="log_box">
      <pre>
          <div v-for="(item, index) of logData" :key="index">{{ item }}</div>
        </pre>
    </div> -->
  </div>
</template>
<script setup>
import { ref, onMounted, nextTick } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";

// WebRTC 相关变量
const localVideo = ref(null);
const remoteVideo = ref(null);
const isRoomEmpty = ref(true); // 判断房间是否为空

let localStream; // 本地流数据
let peerConnection; // RTC连接对象
let signalingSocket; // 信令服务器socket对象
let userId; // 当前用户ID
let roomId = "";
let oppositeUserId; // 对方用户ID
let isJoin = ref(false)
let videoType = ref("1") // 1: 请求通话， 2：正在通话， 3：退出通话

let logData = ref(["日志初始化..."]);

// 请求根路径
let BaseUrl = "http://localhost:19090"

// candidate信息
let candidateInfo = "";

// 发起端标识
let offerFlag = false;

// 房间状态文本
let roomStatusText = ref("点击‘加入房间’开始音视频聊天");

// STUN 服务器，
const iceServers = [
  {
    urls: "stun:stun.l.google.com:19302"  // Google 的 STUN 服务器
  },
  {
    urls: "stun:自己的公网IP:3478" // 自己的Stun服务器
  },
  {
    urls: "turn:自己的公网IP:3478",   // 自己的 TURN 服务器
    username: "maohe",
    credential: "maohe"
  }
];
// ============< 看这 >================
// 没有搭建STUN和TURN服务器的使用如下ice配置即可
// const iceServers = [
//   {
//     urls: "stun:stun.l.google.com:19302"  // Google 的 STUN 服务器
//   }
// ];

onMounted(() => {
  // window.addEventListener('message', (e) => {
  //   let res = JSON.parse(e.data)
  //   roomId = res.roomId
  //   userId = res.ownId
  //   oppositeUserId = res.userId
  //   videoType.value = res.videoType
  //   if (videoType.value == "1"){
  //     joinRoomHandle()
  //   }
  // });
  let urls = window.location.search.split('?')[1].split('&')

  roomId = urls[0].split('=')[1]
  userId = urls[1].split('=')[1]
  oppositeUserId = urls[2].split('=')[1]
  videoType.value = urls[3].split('=')[1]
  if (videoType.value == "1"){
      joinRoomHandle()
    }
})

// 加入房间，开启本地摄像头获取音视频流数据。
function joinRoomHandle() {
  roomStatusText.value = "等待对方加入房间..."
  isJoin.value = true
  getVideoStream();
}

function switchPosition() {
  if (!localVideo.value || !remoteVideo.value) return;

  // 交换视频流
  let tempStream = localVideo.value.srcObject;
  localVideo.value.srcObject = remoteVideo.value.srcObject;
  remoteVideo.value.srcObject = tempStream;

  // 交换本地流和远端流
  [localStream, remoteVideo.value.srcObject] = [remoteVideo.value.srcObject, localStream];

  // 重新绑定到 peerConnection
  if (peerConnection) {
    peerConnection.getSenders().forEach(sender => {
      if (sender.track.kind === "video") {
        sender.replaceTrack(localStream.getVideoTracks()[0]);
      }
    });
  }

  wlog("已切换视频流");
}


// 获取本地视频 模拟从本地摄像头获取音视频流数据
function getVideoStream() {
  const videoElement = document.createElement('video');
  videoElement.src = '../public/a.mp4'; // 本地视频文件
  videoElement.loop = true;
  videoElement.muted = true;

  videoElement.onloadedmetadata = () => {
    // 设置 video 元素的流为本地音视频流
    const stream = videoElement.captureStream();
    localStream = stream;
    localVideo.value.srcObject = stream;
    wlog(`获取本地流成功~`)
    createPeerConnection(); // 创建RTC对象，监听candidate
  };

  videoElement.play();
}


// 初始化 WebSocket 连接
function initWebSocket() {
  wlog("开始连接websocket")
  // 连接ws时携带用户ID
  signalingSocket = new WebSocket(`ws://localhost:19090/rtc?roomId=${roomId}&userId=${userId}`);

  signalingSocket.onopen = () => {
    wlog('WebSocket 已连接');
  };

  // 消息处理
  signalingSocket.onmessage = (event) => {
    handleSignalingMessage(event.data);
  };
};

// 消息处理器 - 解析器
function handleSignalingMessage(message) {
  wlog("收到ws消息，开始解析...")
  wlog(message)
  let parseMsg = JSON.parse(message);
  wlog(`解析结果：${parseMsg}`);

  if (parseMsg.type == "join") {
    joinHandle(parseMsg.data);
  } else if (parseMsg.type == "offer") {
    wlog("收到发起端offer，开始解析...");
    offerHandle(parseMsg.data);
  } else if (parseMsg.type == "answer") {
    wlog("收到接收端的answer，开始解析...");
    answerHandle(parseMsg.data);
  }else if(parseMsg.type == "candidate"){
    wlog("收到远端candidate，开始解析...");
    candidateHandle(parseMsg.data);
  } else if (parseMsg.type == 'leave') {
    console.log('关闭通话')
  }

}

// 远端Candidate处理器
async function candidateHandle(candidate){
  peerConnection.addIceCandidate(new RTCIceCandidate(candidate));
  wlog("+++++++ 本端candidate设置完毕 ++++++++");
}

// 接收端的answer处理
async function answerHandle(answer) {
  wlog("将answer设置为远端信息");
  peerConnection.setRemoteDescription(new RTCSessionDescription(answer)); // 设置远端SDP
}

// 发起端offer处理器
async function offerHandle(offer) {
  wlog("将发起端的offer设置为远端媒体信息");
  await peerConnection.setRemoteDescription(new RTCSessionDescription(offer));
  wlog("创建Answer 并设置到本地");
  let answer = await peerConnection.createAnswer()
  await peerConnection.setLocalDescription(answer);

  wlog("发送answer给发起端");
  // 构造answer消息发送给对端
  let paramObj = {
    userId: oppositeUserId,
    type: "answer",
    data: JSON.stringify(answer)
  }
  // 执行发送
  // const res = await axios.post(`${BaseUrl}/rtcs/sendMessage`, paramObj);
  signalingSocket.send(JSON.stringify(paramObj));
}

// 加入处理器
function joinHandle(userIds) {
  // 判断连接的用户个数
  if (userIds.length == 1 && userIds[0] == userId) {
    wlog("标识为发起端，等待对方加入房间...")
    isRoomEmpty.value = true;
    // 存在一个连接并且是自身，标识我们是发起端
    offerFlag = true;
  } else if (userIds.length > 1) {
    // 对方加入了
    wlog("对方已连接...")
    isRoomEmpty.value = false;

    // 取出对方ID
    for (let id of userIds) {
      if (id != userId) {
        oppositeUserId = id;
      }
    }

    wlog(`对端ID: ${oppositeUserId}`)
    // 开始交换SDP和Candidate
    swapVideoInfo()
  }
}

// 交换SDP和candidate
async function swapVideoInfo() {
  wlog("开始交换Sdp和Candidate...");
  // 检查是否为发起端，如果是创建offer设置到本地，并发送给远端
  if (offerFlag) {
    wlog(`发起端创建offer`)
    let offer = await peerConnection.createOffer()
    await peerConnection.setLocalDescription(offer); // 将媒体信息设置到本地
    wlog("发启端设置SDP-offer到本地");

    // 构造消息ws发送给远端
    let paramObj = {
      userId: oppositeUserId,
      type: "offer",
      data: JSON.stringify(offer)
    };

    wlog(`构造offer信息发送给远端：${paramObj}`)

    // 执行发送
    // const res = await axios.post(`${BaseUrl}/rtcs/sendMessage`, paramObj);
    signalingSocket.send(JSON.stringify(paramObj));

  }
}

// 将candidate信息发送给远端
async function sendCandidate(candidate) {
  // 构造消息ws发送给远端
  let paramObj = {
    userId: oppositeUserId,
    type: "candidate",
    data: JSON.stringify(candidate)
  };

  wlog(`构造candidate信息发送给远端：${paramObj}`);

  // 执行发送
  // const res = await axios.post(`${BaseUrl}/rtcs/sendMessage`, paramObj);
  signalingSocket.send(JSON.stringify(paramObj));

}

// 创建RTC连接对象并监听和获取condidate信息
function createPeerConnection() {
  wlog("开始创建PC对象...")
  peerConnection = new RTCPeerConnection(iceServers);
  wlog("创建PC对象成功")
  // 创建RTC连接对象后连接websocket
  initWebSocket();

  // 监听网络信息（ICE Candidate）
  peerConnection.onicecandidate = (event) => {
    if (event.candidate) {
      candidateInfo = event.candidate;
      wlog("candidate信息变化...");
      // 将candidate信息发送给远端
      setTimeout(()=>{
        sendCandidate(event.candidate);
      }, 150)
    }
  };

  // 监听远端音视频流
  peerConnection.ontrack = (event) => {
    nextTick(() => {
      wlog("====> 收到远端数据流 <=====")
      if (!remoteVideo.value.srcObject) {
        remoteVideo.value.srcObject = event.streams[0];
        remoteVideo.value.play();  // 强制播放
      }
    });
    // remoteVideo.value.srcObject = event.streams[0];
  };

  // 监听ice连接状态
  peerConnection.oniceconnectionstatechange = () => {
    wlog(`RTC连接状态改变：${peerConnection.iceConnectionState}`);
  };


  // 添加本地音视频流到 PeerConnection
  localStream.getTracks().forEach(track => {
    peerConnection.addTrack(track, localStream);
  });
}

function exitRoomHandle(){
  let data = {
    videoType: "3",
    from: userId,
    to: oppositeUserId,
  }
  window.parent.postMessage(JSON.stringify(data), '*');
}

// 日志编写
function wlog(text) {
  logData.value.unshift(text);
}

// 给用户生成随机ID.
function generateRandomId() {
  userId = Math.random().toString(36).substring(2, 12); // 生成10位的随机ID
  wlog(`分配到ID:${userId}`)
}
</script>

<style scoped>
.video-chat {
  width: 96%;
  height: 90%;
  padding: 10px;
}


.remote_video {
  margin-left: 20px;
  position: absolute;
  width: 100px;
  height: 100px;
  top: 0;
  right: 10px;
  background-color: #f1f1f1;
  video {
    width: 100%;
    height: 100%;
  }
}

.self_video {
  width: 100%;
  height: 100%;
  background-color: #e1e1e1;
  video {
    width: 100%;
    height: 100%;
    max-height: 420px;
  }
}

.video_box {
  position: relative;
  width: 100%;
  height: 100%;
}

.join_room_btn{
  position: absolute;
  top: 70%;
  left: 46%;
}

.join_room_btn {
  button{
    border: none;
    height: 30px;
    width: 80px;
    border-radius: 10px;
    color: white;
    margin-top: 10px;
    cursor: pointer;
    font-size: 13px;
  }
  button:first-child {
    background-color: rgb(119 178 63);
    margin-right: 10px;
  }
  button:last-child {
    background-color: rgb(204, 61, 35);
    margin-right: 10px;
  }
}

.text_tip {
  font-size: 13px;
  color: #484848;
  padding: 6px;
}

pre {
  width: 600px;
  height: 300px;
  background-color: #d4d4d4;
  border-radius: 10px;
  padding: 10px;
  overflow-y: auto;
}

pre div {
  padding: 4px 0px;
  font-size: 15px;
}

.userId{
  color: #3669ad;
}

.video-chat p{
  font-weight: 600;
  color: #b24242;
}
</style>